const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 格式化为 yyyy-MM-dd HH:mm:ss
const formatYMDHMS = ts => {
  if (ts === null || ts === undefined || ts === '') return ''
  // If already a datetime string 'yyyy-MM-dd HH:mm:ss' or 'yyyy-MM-dd', normalize
  if (typeof ts === 'string') {
    const s = ts.trim()
    // full datetime
    if (/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}$/.test(s)) return s
    // date only -> append midnight
    if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return `${s} 00:00:00`
    // try parseable string
    const parsed = Date.parse(s)
    if (!Number.isNaN(parsed)) {
      const d2 = new Date(parsed)
      const Y2 = d2.getFullYear()
      const M2 = String(d2.getMonth() + 1).padStart(2, '0')
      const D2 = String(d2.getDate()).padStart(2, '0')
      const h2 = String(d2.getHours()).padStart(2, '0')
      const m2 = String(d2.getMinutes()).padStart(2, '0')
      const s2 = String(d2.getSeconds()).padStart(2, '0')
      return `${Y2}-${M2}-${D2} ${h2}:${m2}:${s2}`
    }
  }
  const t = typeof ts === 'number' ? ts : Number(ts)
  if (Number.isNaN(t)) return ''
  const d = new Date(t)
  const Y = d.getFullYear()
  const M = String(d.getMonth() + 1).padStart(2, '0')
  const D = String(d.getDate()).padStart(2, '0')
  const h = String(d.getHours()).padStart(2, '0')
  const m = String(d.getMinutes()).padStart(2, '0')
  const s = String(d.getSeconds()).padStart(2, '0')
  return `${Y}-${M}-${D} ${h}:${m}:${s}`
}

module.exports = {
  formatTime
  , formatYMDHMS
}

